package com.reactim.user.controller;

import com.reactim.user.dto.Result;
import com.reactim.user.dto.UserLoginRequest;
import com.reactim.user.dto.UserRegisterRequest;
import com.reactim.user.dto.response.LoginResponse;
import com.reactim.user.dto.UserResponse;
import com.reactim.user.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
// 暂时移除Authentication依赖
// import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Mono;

import jakarta.validation.Valid;

/**
 * 认证控制器
 * 处理用户认证相关的API请求
 */
@Slf4j
@RestController
@RequestMapping("/api/auth")
@RequiredArgsConstructor
public class AuthController {

    private final UserService userService;

    /**
     * 用户登录
     */
    @PostMapping("/login")
    public Mono<Result<LoginResponse>> login(@Valid @RequestBody UserLoginRequest request) {
        return userService.login(request)
                .map(token -> {
                    // 构建登录响应
                    LoginResponse response = LoginResponse.builder()
                            .token(token)
                            .refreshToken(token) // 简化处理，实际应该生成不同的refreshToken
                            .expiresIn(86400L) // 24小时
                            .user(userService.getUserByUsername(request.getUsername()).block())
                            .build();
                    return Result.success(response);
                })
                .doOnSuccess(result -> log.info("用户登录成功: {}", request.getUsername()))
                .doOnError(error -> log.error("用户登录失败: {}", request.getUsername(), error));
    }

    /**
     * 用户注册
     */
    @PostMapping("/register")
    public Mono<Result<UserResponse>> register(@Valid @RequestBody UserRegisterRequest request) {
        return userService.register(request)
                .map(Result::success)
                .doOnSuccess(result -> log.info("用户注册成功: {}", request.getUsername()))
                .doOnError(error -> log.error("用户注册失败: {}", request.getUsername(), error));
    }

    /**
     * 用户登出（暂时简化，不使用Authentication）
     */
    @PostMapping("/logout")
    public Mono<Result<Void>> logout(@RequestParam(required = false) String username) {
        // 这里可以添加登出逻辑，比如将token加入黑名单
        log.info("用户登出: {}", username != null ? username : "unknown");
        return Mono.just(Result.success(null));
    }

    /**
     * 获取当前用户信息（暂时简化，不使用Authentication）
     */
    @GetMapping("/me")
    public Mono<Result<UserResponse>> getCurrentUser(@RequestParam String username) {
        return userService.getUserByUsername(username)
                .map(Result::success)
                .doOnSuccess(result -> log.debug("获取当前用户信息: {}", username));
    }

    /**
     * 刷新Token
     */
    @PostMapping("/refresh")
    public Mono<Result<LoginResponse>> refreshToken(@RequestBody RefreshTokenRequest request) {
        // 简化处理，实际应该验证refreshToken的有效性
        return userService.getUserByUsername(request.getUsername())
                .map(user -> {
                    String newToken = "new-jwt-token"; // 实际应该生成新的JWT
                    LoginResponse response = LoginResponse.builder()
                            .token(newToken)
                            .refreshToken(request.getRefreshToken())
                            .expiresIn(86400L)
                            .user(user)
                            .build();
                    return Result.success(response);
                })
                .doOnSuccess(result -> log.info("Token刷新成功: {}", request.getUsername()));
    }

    /**
     * 刷新Token请求
     */
    public static class RefreshTokenRequest {
        private String refreshToken;
        private String username;
        
        // getters and setters
        public String getRefreshToken() { return refreshToken; }
        public void setRefreshToken(String refreshToken) { this.refreshToken = refreshToken; }
        public String getUsername() { return username; }
        public void setUsername(String username) { this.username = username; }
    }
}